package itsm.isperp.module.controller.app;

import itsm.isperp.framework.collection.tree.ITreeNode;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.web.domain.CountQuery;
import itsm.isperp.framework.web.request.DefaultCountQuery;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.service.app.AppMessageSenderService;
import itsm.isperp.module.service.app.AppMessageService;
import itsm.isperp.module.service.app.AppMessageSuccessService;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 系统帮助的控制器
 * 
 * @author lizx
 * @date 2013-7-27
 */
@Controller
@RequestMapping("app/message")
public class AppMessageController {

	@Autowired
	protected AppMessageService appMessageService;

	@Autowired
	protected AppMessageSuccessService appMessageSuccessService;

	@Autowired
	protected AppMessageSenderService appMessageSenderService;

	/**
	 * 用户消息管理列表
	 * 
	 * @return
	 */
	@RequestMapping("userMessages")
	public ModelAndView userMessages() {
		ModelAndView mv = new ModelAndView("app/message/userMessages");

		List<Map<String, Object>> messages = appMessageSuccessService
				.findMyMessage(false, 10);

		mv.addObject("messages", messages);
		return mv;
	}

	/**
	 * 获取用户消息总数
	 * 
	 * @return
	 */
	@RequestMapping("userMessagesCount")
	@ResponseBody
	public Map<String, Object> userMessagesCount() {
		String username = ContextHolder.getLoginUsername();
		return appMessageSuccessService.findMyMessageAllCount(username);

	}

	@RequestMapping(value = "read/{id}")
	@ResponseBody
	public ResultMessage read(@PathVariable("id") String id,
			HttpServletRequest req) throws Exception {

		appMessageSuccessService.markReadMessage(id);
		return ResultMessage.success();
	}

	@RequestMapping(value = "readAll")
	@ResponseBody
	public ResultMessage readAll(HttpServletRequest req) throws Exception {

		appMessageSuccessService.markReadMessage();
		return ResultMessage.success();
	}

	// ~-----------------------信箱---------------------------------

	/**
	 * 我的信箱
	 * 
	 */
	@RequestMapping("myMessageBoxView")
	public ModelAndView myMessageBoxView() {
		ModelAndView mv = new ModelAndView("app/message/myMessageBoxView");

		return mv;
	}

	protected CountQuery getMyCountQuery() {
		return getCountQuery(false);
	}

	protected CountQuery getAllCountQuery() {
		return getCountQuery(true);
	}

	protected CountQuery getCountQuery(boolean all) {
		CountQuery cq = new DefaultCountQuery(
				" (SELECT  app_message_success.*,null AS error_reason,1 AS send_result FROM app_message_success UNION ALL SELECT app_message_failed.*,0 AS send_result FROM app_message_failed)  ");

		String strReceiver = "";

		if (!all) {
			strReceiver = " receiver_id = '" + ContextHolder.getLoginUsername()
					+ "' AND ";
		}

		cq.addCountFilter("已收站内信", strReceiver
				+ " message_type='MSG'  AND send_result=1 ");
		cq.addCountFilter("已收邮件", strReceiver
				+ "   message_type='EMAIL'  AND send_result=1 ");
		cq.addCountFilter("已收短信", strReceiver
				+ "  message_type='SMS'  AND send_result=1 ");
		cq.addCountFilter("发送失败消息", strReceiver + "  send_result=0 ");
		cq.addCountFilter("我的发件箱",
				" sender_id ='" + ContextHolder.getLoginUsername()
						+ "' AND send_result=1 ");
		return cq;
	}

	@RequestMapping("myMessageMenu")
	@ResponseBody
	public ITreeNode[] myMessageMenu() {
		CountQuery cq = this.getMyCountQuery();

		// ITreeNode tn = new AbstractTreeNode();
		//
		// tn.setName("我的发件箱("
		// + appMessageSenderService.findAllCount(ContextHolder
		// .getLoginUsername()) + ")");
		// tn.setId("我的发件箱");
		// tn.setTreenodePath("我的发件箱");

		return cq.getTreeNodes();
	}

	@RequestMapping("view")
	public ModelAndView view(String id) {
		ModelAndView mv = new ModelAndView("app/message/view");

		Map<String, Object> model = this.appMessageService
				.findOneDetailById(id);

		mv.addObject("model", model);
		// 设置为已读
		appMessageSuccessService.markReadMessage(id);
		return mv;
	}

	@RequestMapping("listDetails")
	@ResponseBody
	public PageResponse<Map<String, Object>> listDetails(JqGridRequest request,
			HttpServletRequest req) {
		String queryPath = req.getParameter("queryPath");
		String all = req.getParameter("all");
		CountQuery cq = null;
		if ("1".equals(all)) {

			cq = getAllCountQuery();
		} else {

			cq = getMyCountQuery();
		}

		if (cq != null) {
			request.setCountQuery(cq);
			request.setQueryPath(queryPath);

		}

		return this.appMessageService.findAllDetailByRequest(request).toPage();

	}

	// ~-----------------------信箱---------------------------------

	protected CountQuery getCountQueryBySourceId() {
		CountQuery cq = new DefaultCountQuery("    app_message_success   ");

		cq.addCountFilter("站内消息",
				"  message_type IN ('MSG','LEAVEMSG')  AND  message_level=1 ");

		cq.addCountFilter("邮件和短信",
				"  message_type IN ('SMS','EMAIL')  AND  message_level=1 ");

		cq.addCountFilter("系统消息", "   message_level=0   ");

		return cq;
	}

	/**
	 * 根据业务源id获取关联消息列表
	 * 
	 * @param sourceId
	 *            业务源id
	 * @param req
	 *            数据请求
	 * @return 列表json数据
	 */
	@RequestMapping("listBySourceId")
	@ResponseBody
	public PageResponse<Map<String, Object>> listBySourceId(String all,
			String sourceId, JqGridRequest request, HttpServletRequest req) {
		if (StringUtils.isEmpty(sourceId)) {
			return null;
		}

		String queryPath = req.getParameter("queryPath");
		CountQuery cq = getCountQueryBySourceId();
		if (cq != null) {
			request.setCountQuery(cq);
			request.setQueryPath(queryPath);

		}

		return this.appMessageSuccessService.findAllRelationBySourceId(request,
				sourceId, "1".equals(all)).toPage();
	}

	/**
	 * 关联消息
	 */
	@RequestMapping("relationMessageView")
	public ModelAndView relationMessageView(String sourceId, String all,
			HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("app/message/relationMessageView");
		mv.addObject("sourceId", sourceId);
		mv.addObject("all", all);
		return mv;
	}

	@RequestMapping("findCountsBySourceIds")
	@ResponseBody
	public List<Map<String, Object>> findCountsBySourceIds(String all,
			HttpServletRequest req) {

		String ids = req.getParameter("ids");
		if (StringUtils.isEmpty(ids)) {
			return null;
		}

		String[] sourceIds = ids.substring(1).split(",");

		List<Map<String, Object>> l = this.appMessageSuccessService
				.findRelationCountsBySourceIds(sourceIds, "1".equals(all));
		return l;
	}

	/**
	 * 我的信箱
	 * 
	 */
	@RequestMapping("allMessageBoxView")
	public ModelAndView allMessageBoxView() {
		ModelAndView mv = new ModelAndView("app/message/allMessageBoxView");

		return mv;
	}

}
